package com.example.droidwarehouse.async;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;

import android.os.AsyncTask;
import android.util.Log;

import com.example.droidwarehouse.MainActivity;

/**
 * Asynchronous communication with the webservice
 * 
 * @author Bibek Shrestha <bibek.shrestha@tum.de>
 * @since 26.11.2012
 */
public class Communicator extends AsyncTask<Object, Void, String>
{

    /**
     * @param bgParams
     *            [0] String URL to communicate to
     * 
     *            [1] Map<String, String> a map of parameters to be sent to the
     *            server
     */
    @SuppressWarnings("unchecked")
    @Override
    protected String doInBackground(Object... bgParams)
    {
        String targetURL = (String) bgParams[0];
        Map<String, String> params = (Map<String, String>) bgParams[1];

        Log.d(MainActivity.TAG, params.toString());
        URL url;
        HttpURLConnection connection = null;
        String urlParameters = "";
        try
        {
            // Build parameter strings
            for (String paramKey : params.keySet())
            {
                if (!paramKey.equals(""))
                {
                    if (params.get(paramKey) == null || params.get(paramKey).equals(""))
                    {
                        urlParameters += paramKey + "&";
                    }
                    else
                    {
                        urlParameters += paramKey + "=" + URLEncoder.encode(params.get(paramKey), "UTF-8") + "&";
                    }
                }
            }
            if (urlParameters.length() > 0)
            {
                urlParameters = urlParameters.substring(0, urlParameters.length() - 1);
            }
            Log.d(MainActivity.TAG, "Encoded URL Parameters : " + urlParameters);

            // Create connection
            url = new URL(targetURL);
            Log.d(MainActivity.TAG, "Connectiong to URL: " + targetURL);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

            connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length));
            connection.setRequestProperty("Content-Language", "en-US");

            connection.setUseCaches(false);
            connection.setDoInput(true);
            connection.setDoOutput(true);

            // Send request
            DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
            wr.writeBytes(urlParameters);
            wr.flush();
            wr.close();

            // Get Response
            InputStream is = connection.getInputStream();
            BufferedReader rd = new BufferedReader(new InputStreamReader(is));
            String line;
            StringBuffer response = new StringBuffer();
            while ((line = rd.readLine()) != null)
            {
                response.append(line);
                response.append('\r');
            }
            rd.close();
            return response.toString();
        }
        catch (Exception e)
        {

            e.printStackTrace();
            return null;

        }
        finally
        {

            if (connection != null)
            {
                connection.disconnect();
            }
        }
    }
}
